<?php
declare (strict_types=1);

namespace app\admin\validates;

use think\Validate;

/**
 * User验证器
 */
class UserValidate extends Validate
{
    /**
     * 验证规则
     * @var array
     */
    protected $rule = [
        'id' => 'require|number',
        'nickname' => 'chsDash|max:15',
        'code' => 'require|number',
        'area_code' => 'require',
        'phone' => 'require|checkMobile',
        'new_password' => 'require|max:32|alphaNum',
        'rep_password' => 'require|max:32|alphaNum',
        'name' => 'chsDash|max:50',
        'email' => 'email|max:50',
        'wechat' => 'chsDash|max:50',
        'qq' => 'chsDash|max:15',
        'birthday' => 'date|max:50',
        'address' => 'chsDash|max:255',
        'gender' => 'number|between:0,2',
    ];

    /**
     * 验证字段描述
     * @var string[]
     */
    protected $field = [
        'id' => 'ID',
        'nickname' => '昵称',
        'code' => '验证码',
        'area_code' => 'require',
        'phone' => '手机号',
        'new_password' => '新密码',
        'rep_password' => '重复密码',
        'name' => '姓名',
        'email' => '邮箱',
        'wechat' => '微信号',
        'qq' => 'QQ号',
        'birthday' => '生日',
        'address' => '地址',
        'gender' => '性别',
    ];

    /**
     * 验证场景
     * @var array
     */
    protected $scene = [
        'addUser' => ['nickname', 'code', 'area_code', 'phone', 'new_password', 'rep_password'],
        'retrievePwd' => ['code', 'area_code', 'phone', 'new_password', 'rep_password'],
        'getSmsCode' => ['area_code', 'phone'],
        'edit' => ['nickname', 'name', 'email', 'wechat', 'qq', 'birthday', 'address', 'gender'],
    ];

    /**
     * 验证手机号格式
     * @param string $value
     * @param string $rule
     * @param array $data
     * @return bool|string
     */
    protected function checkMobile(string $value, string $rule, array $data)
    {
        if (isset($data['area_code']) && $data['area_code'] === '+86') {
            $preg = '/^1[3-9]\d{9}$/';
            if (!preg_match($preg, $value)) {
                return '手机号码格式错误';
            }
        }
        return true;
    }


}